package com.liang.dao.role;

import com.liang.dao.BaseDao;
import com.liang.pojo.Role;
import com.mysql.cj.util.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RoleDaoImpl implements RoleDao {
    @Override
    public List<Role> getRoleList(Connection connection, String roleCode, String roleName) {
        List<Role> roleList = new ArrayList<>();
        PreparedStatement pr = null;
        ResultSet rs = null;
        if(connection!=null){
            try {
                StringBuffer stringBuffer = new StringBuffer();
                ArrayList<Object> list = new ArrayList<>();
                stringBuffer.append("select * from smbms_role");
                if (!StringUtils.isNullOrEmpty(roleCode)) {
                    stringBuffer.append(" where roleCode like ?");
                    list.add("%" + roleCode + "%");
                } else if (!StringUtils.isNullOrEmpty(roleName)) {
                    stringBuffer.append(" where roleName like ?");
                    list.add("%" + roleName + "%");
                }else if (!StringUtils.isNullOrEmpty(roleCode)&&!StringUtils.isNullOrEmpty(roleName)){
                    stringBuffer.append(" where roleName like ? and roleCode like ?");
                    list.add("%" + roleName + "%");
                    list.add("%" + roleCode + "%");
                }
                Object [] params = list.toArray();
                rs = BaseDao.execute(connection, pr, rs, stringBuffer.toString(), params);
                while (rs.next()){
                    Role role = new Role();
                    role.setId(rs.getInt("id"));
                    role.setRoleCode(rs.getString("roleCode"));
                    role.setRoleName(rs.getString("roleName"));
                    role.setCreateBy(rs.getInt("createdBy"));
                    role.setCreationDate(rs.getDate("creationDate"));
                    role.setModifyBy(rs.getInt("modifyBy"));
                    role.setModifyDate(rs.getDate("modifyDate"));
                    roleList.add(role);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                BaseDao.closeResource(rs, pr, connection);
            }
        }


        return roleList;
    }
}
